package com.nk.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.nk.domain.PageListRes;
import com.nk.domain.Permission;
import com.nk.domain.QueryVo;
import com.nk.domain.Role;
import com.nk.mapper.RoleMapper;
import com.nk.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Transactional
public class RoleServiceImpl implements RoleService {

    @Autowired
    private RoleMapper roleMapper;

    @Override
    public PageListRes getRoles(QueryVo vo) {
        Page<Object> page = PageHelper.startPage(vo.getPage(),vo.getRows());
        List<Role> roleList = roleMapper.selectAll();
        PageListRes pageListRes = new PageListRes();
        pageListRes.setRows(roleList);
        pageListRes.setTotal(page.getTotal());
        return pageListRes;
    }

    @Override
    public void saveRole(Role role) {
        roleMapper.insert(role);
        for (Permission permission : role.getPermissionList()) {
            roleMapper.insertRoleAndPermissionRel(role.getRid(),permission.getPid());
        }
    }

    @Override
    public List<Permission> getPermissionByRid(long rid) {
        List<Permission> permissionList = roleMapper.getPermissionByRid(rid);
        return permissionList;
    }

    @Override
    public void updateRole(Role role) {

        // 删除之前的权限
        roleMapper.deletePermissionByRole(role.getRid());
        for (Permission permission : role.getPermissionList()) {
            roleMapper.insertRoleAndPermissionRel(role.getRid(),permission.getPid());
        }
        roleMapper.updateByPrimaryKey(role);
    }

    @Override
    public int deleteRoleByID(long rid) {
        //删除权限
        roleMapper.deletePermissionByRole(rid);
        return roleMapper.deleteByPrimaryKey(rid);
    }

    @Override
    public List<Role> selectRoles() {
        List<Role> roleList = roleMapper.selectAll();
        return roleList;
    }

    @Override
    public List<Long> getRoleIDByEid(Long id) {

        return roleMapper.getRoleIDByEid(id);
    }

}
